package com.zhuss.juc;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadPoolFactory {
	
	private static ThreadPoolExecutor singlePool;
	
	private static ReentrantLock lock = new ReentrantLock();
	
	public static ThreadPoolExecutor getInstance() {
		lock.lock();
		try {
			if (singlePool == null) {
				singlePool = new ThreadPoolExecutor(2, 5, 1, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());
			}
		} finally {
			lock.unlock();
		}
		return singlePool;
	}
	
	private static List<ThreadPoolExecutor> list = new CopyOnWriteArrayList<>();
	
	public static void main(String[] args) throws InterruptedException {
		int i = 5000;
		CountDownLatch latch = new CountDownLatch(i);
		for (int j = 0; j < i; j ++) {
			new Thread(()-> {
				list.add(ThreadPoolFactory.getInstance());
			}).start();
			latch.countDown();
		}
		latch.await();
		for (ThreadPoolExecutor item : list) {
			System.out.println(item);
		}
	}

}
